package com.app.micaihu.manager;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.infor.UserInfor;
import com.app.micaihu.bean.infor.UserTask;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.custom.view.dialog.CustomDialog;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.utils.CollectUtils;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.utils.InteractiveUtils;
import com.app.micaihu.view.login.activity.QuickLoginActivity;
import com.app.micaihu.view.user.userinfo.activity.WebActivity;
import com.app.utils.biz.Biz;
import com.app.utils.util.AppTools;
import com.app.utils.util.ToastUtils;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.google.gson.reflect.TypeToken;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;
import java.util.Observable;

/**
 * Created by Guo on 2016/7/13.
 * <p>
 * 用户信息的管理类:
 */
public class UserInforManager implements View.OnClickListener {

    public static final String TOKEN_ERROR = "17";//TOKEN错误

    public static final String UNBIND_PHONE_ERROR = "157";//没有绑定手机的登录错误 code_(从2.2开始);


    private static volatile UserInforManager mUserInforManager;

    private UserInfor userInfor;//用户信息类

    private String mPageName;

    public static final int TO_LOGIN_REQUESTCODE = 190;
    private Activity activity;

    private UserInforManager() {
        this.mPageName = "UserInforManager";
    }


    public static UserInforManager getInstance() {
        if (mUserInforManager == null) {
            synchronized (UserInforManager.class) {
                if (mUserInforManager == null) {
                    mUserInforManager = new UserInforManager();
                }
            }
        }
        return mUserInforManager;
    }

    /**
     * 此方法来判断用户是否登录,返回为true,则表明userinfor和task均不为空
     *
     * @return
     */
    public boolean isLogin() {
        return this.userInfor != null && this.userInfor.getTask() != null;
    }

    /**
     * 设置用户信息
     *
     * @param userInfor
     */
    public void setUserInfor(UserInfor userInfor) {
        this.userInfor = userInfor;
        if (this.userInfor != null) {
            this.userInfor.getIsGetTask("每日登录");
        } else {
        }
    }

    /**
     * 拿取用户信息,如果内存中没有,则会拿取数据库中的
     *
     * @return
     */
    public UserInfor getUserInfor() {
        //拿取本地存储的->c
        String userInfoStr = Biz.getInstance().getUserInfo();
        if (!StringUtils.isEmpty(userInfoStr)) {
            this.userInfor = GsonUtils.fromJson(userInfoStr, UserInfor.class);
        }
        String userTaskStr = Biz.getInstance().getUserTask();
        if (!StringUtils.isEmpty(userTaskStr)) {
            UserTask userTask = GsonUtils.fromJson(userTaskStr, UserTask.class);
            if (this.userInfor != null && userTask != null) {
                this.userInfor.setTask(userTask);
            }
        }
        return this.userInfor;
    }


    /**
     * 本地登录/伪登录
     *
     * @return
     */
    public void localWeiLogin(final Context context) {
        if (getUserInfor() != null) {
            //请求伪登录
            String uid = userInfor.getUid();//拿到内存中的uid(也是本地的)
            ParamMap params = new ParamMap();
            params.putEncode("uid", uid);
            params.putEncode("imei", AppTools.getIMEI());
            params.putEncode("version", AppTools.getVersionCode() + "");
            params.putEncode("type", TypeConstant.PLATFORM);
            HttpUtils.ParmsMapMD5(params);

            addPostRequest(URIContant.WEILOGIN, new TypeToken<DataBean<UserInfor>>() {
            }.getType(), params, new HttpListener<DataBean<UserInfor>>() {
                @Override
                public void onError(VolleyError error) {
                }

                @Override
                public void onSuccess(DataBean<UserInfor> response) {//成功了
                    try {
                        if (response.noError()) {
                            userInfor = response.getData();//得到网络最新数据
                            userInfor.getIsGetTask("每日登录");
                            //将最新的网络的userinfor保存到数据库
                            UserInforManager.getInstance().saveUserInfor(userInfor);
                            //拉取任务数据
                            UserInforManager.getInstance().getUserTask(context, false);
                        } else if (TextUtils.equals(response.getCode(), UNBIND_PHONE_ERROR)
                                && response.getData() != null
                                && !TextUtils.isEmpty(response.getData().getUid())) {
                            UserInforManager.getInstance().setUserInfor(null);
                            Biz.getInstance().setUserInfo("");
                            Biz.getInstance().setUserTask("");
                            InteractiveUtils.getInstance().readLaudFromLocal();
                            toLoginPage((Activity) context);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }


    /**
     * 获取任务中心接口数据的
     *
     * @param context 上下文变量 必须传本页面的
     * @param finish  是否finish当前页面
     */
    public void getUserTask(final Context context, final boolean finish) {
        //如果Uid为null->第一次失败
        if (getUserInfor() == null || TextUtils.isEmpty(UserInforManager.getInstance().getUserInfor().getUid())) {
            if (finish) {
                ToastUtils.makeText("获取用户信息失败,请稍后再试");
                DialogUtils.getInstance().dismissProgressDialog();
            }
        } else {
            ParamMap params = new ParamMap();
            params.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());
            HttpUtils.ParmsMapMD5(params);
            addPostRequest(URIContant.TASK, new TypeToken<DataBean<UserTask>>() {
            }.getType(), params, new HttpListener<DataBean<UserTask>>() {
                @Override
                public void onError(VolleyError error) {
                    ToastUtils.makeText(AppApplication.getInstance().getResources().getString(R.string.neterror));
                    DialogUtils.getInstance().dismissProgressDialog();
                }

                @Override
                public void onSuccess(DataBean<UserTask> response) {
                    if (!response.noError()) {
                        DialogUtils.getInstance().dismissProgressDialog();
                    } else {
                        UserTask userTask = response.getData();
                        if (userTask == null) {
                            ToastUtils.makeText("获取用户信息失败,请稍后重试");
                            DialogUtils.getInstance().dismissProgressDialog();
                        } else {
                            //如果是升级了并且 不是登录的界面,
                            if (userTask.getIsLevelUp() && !finish) {
                                if (context instanceof Activity) {//弹窗成功后 将是否升级置为flase
                                    ToastUtils.cancelToast();
                                    CustomDialog.getInstance().showLevelUpDialog((Activity) context, userTask.getPrevRankName(), userTask.getRankName());
                                    if (getUserInfor() != null && getUserInfor().getTask() != null) {
                                        getUserInfor().getTask().setIsLevelUp("0");
                                        userTask.setIsLevelUp("0");
                                    }
                                }
                            }
                            saveUserTask(userTask);
                            LiveEventBus.get(Config.EventBus.taskSuccess).post(true);
                            if (userTask.getIsEvaluated() && !finish && context instanceof Activity) {
                                isShowMarketDialog((Activity) context);
                            }
                            InteractiveUtils.getInstance().readLaudFromLocal();
                            InteractiveUtils.getInstance().getAllBlackList();

                            if (finish) {
                                DialogUtils.getInstance().dismissProgressDialog();
                                try {
                                    ((Activity) context).setResult(Activity.RESULT_OK);
                                    ((Activity) context).onBackPressed();
                                    CollectUtils.getInstance().uploadLocalSaveNews();
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }
            });
        }
    }

    /**
     * 是否展示 评分弹窗的逻辑前置方法
     *
     * @param context
     */
    private void isShowMarketDialog(Activity context) {
        String s = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.isShow_marketdialog, "");
        if (TextUtils.isEmpty(s)) {//第一次
            ToastUtils.cancelToast();
            goToMarketDialog(context);
        } else {
            String[] split = s.split("_");
            if (split.length == 2) {
                if (!TextUtils.equals(AppTools.getVersionName(), split[1])
                        && !Boolean.valueOf(split[0])) {
                    ToastUtils.cancelToast();
                    goToMarketDialog(context);
                }
            }
        }
    }


    /**
     * 显示 评分的dialog
     */
    private void goToMarketDialog(Activity activity) {
        this.activity = activity;
        View marketDialog = LayoutInflater.from(activity).inflate(R.layout.dialog_market, null);
        TextView tvOk = (TextView) marketDialog.findViewById(R.id.tv_ok);
        TextView tvRefuse = (TextView) marketDialog.findViewById(R.id.tv_refuse);
        TextView tvCancel = (TextView) marketDialog.findViewById(R.id.tv_cancel);
        tvOk.setOnClickListener(this);
        tvRefuse.setOnClickListener(this);
        tvCancel.setOnClickListener(this);
        HashMap<String, Object> dialogParams = new HashMap<>();
        dialogParams.put("width", 300);
        DialogUtils.getInstance().showCDialog(marketDialog, activity, dialogParams);

        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.isShow_marketdialog, "true_" + AppTools.getVersionName());
    }


    /**
     * 保存UserTask至本地
     *
     * @param userTask Task对象
     */
    public void saveUserTask(UserTask userTask) {
        if (userTask == null) return;
        Biz.getInstance().setUserTask(GsonUtils.toJson(userTask));
        if (this.userInfor != null) {
            this.userInfor.setTask(userTask);
        }

    }


    /**
     * 保存UserInfor至本地
     * 更新如果失败,表示没有,就插入一条
     *
     * @param userInfor
     */
    public void saveUserInfor(UserInfor userInfor) {
        if (userInfor == null) return;
        Biz.getInstance().setUserInfo(GsonUtils.toJson(userInfor));
        // 保存 上一次登录信息
        Biz.getInstance().setLastUserInfo(GsonUtils.toJson(userInfor));
    }


    /**
     * 跳转web页面
     *
     * @param title
     * @param url
     */
    public void toWebActivity(Activity mActivity, String title, String url) {
        try {
            Intent intent = new Intent(mActivity, WebActivity.class);
            intent.putExtra(Config.Extra.title, title);
            intent.putExtra(Config.Extra.url, url);
            mActivity.startActivity(intent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 跳转到登录页面
     *
     * @param actvity
     */

    public void toLoginPage(Activity actvity) {
        if (actvity == null || actvity.isFinishing()) {
            return;
        }
        Intent mIntentLogin = new Intent(actvity, QuickLoginActivity.class);
        actvity.startActivityForResult(mIntentLogin, TO_LOGIN_REQUESTCODE);
        actvity.overridePendingTransition(R.anim.translate_slide_in_bottom, R.anim.slide_out_left);
    }

    /**
     * 弹出升级弹框的方法
     */
    public void showLevelDialog(Activity activity) {
        if (UserInforManager.getInstance().getUserInfor() != null
                && UserInforManager.getInstance().getUserInfor().getTask() != null) {
            UserTask task = UserInforManager.getInstance().getUserInfor().getTask();
            if (task != null && task.getIsLevelUp()) {
                CustomDialog.getInstance().showLevelUpDialog(activity, task.getPrevRankName(), task.getRankName());
                task.setIsLevelUp("0");
                UserInforManager.getInstance().saveUserTask(task);
            }
        }
    }


    /**
     * 获取用户的加密的手机
     *
     * @return
     */
    public String getJiamiPhone() {
        if (getUserInfor() == null) {
            return "";
        }
        String phone = getUserInfor().getMobile();
        String jiamiphone = getUserInfor().getJiamiphone();

        if (TextUtils.isEmpty(phone)) {
            return "";
        }

        if (TextUtils.isEmpty(jiamiphone)) {// 为空,进行加密
            if (phone.length() < 6) {
                jiamiphone = phone;
                return jiamiphone;
            }
            String phone1 = phone.substring(0, 3);
            String phone2 = phone.substring(phone.length() - 2);
            String phone3 = phone.substring(3, phone.length() - 2);
            String phone4 = "";
            for (int i = 0; i < phone3.length(); i++) {
                phone4 += "*";
            }
            jiamiphone = (phone1 + phone4 + phone2);
            return jiamiphone;
        } else {// 判断后两位

            String phoneLast2 = "";
            String jiamiPhoneLast2 = "";
            try {
                phoneLast2 = phone.substring(phone.length() - 2,
                        phone.length());
                jiamiPhoneLast2 = jiamiphone.substring(
                        jiamiphone.length() - 2, jiamiphone.length());
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            if (TextUtils.equals(phoneLast2, jiamiPhoneLast2)) {
                return jiamiphone;
            } else {
                if (phone.length() < 6) {
                    jiamiphone = phone;
                    return jiamiphone;
                }
                String phone1 = phone.substring(0, 3);
                String phone2 = phone.substring(phone.length() - 2);
                String phone3 = phone.substring(3, phone.length() - 2);
                String phone4 = "";
                for (int i = 0; i < phone3.length(); i++) {
                    phone4 += "*";
                }
                jiamiphone = (phone1 + phone4 + phone2);
                return jiamiphone;
            }
        }

    }


    protected void addPostRequest(@NonNull String url, @NonNull Type type, Map<String, String> parms, @NonNull HttpListener<?> httpListener) {

        HttpUtils.addPostRequest(url, type, mPageName, parms, httpListener);
    }


    @Override
    public void onClick(View v) {
        if (v == null) return;
        switch (v.getId()) {
            case R.id.tv_ok:
                Uri uri = Uri.parse("market://details?id=" + activity.getPackageName());
                Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                try {
                    activity.startActivity(intent);
                    activity.overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain);
                } catch (ActivityNotFoundException e) {
                    ToastUtils.showText(AppApplication.getInstance().getString(R.string.set_nomark));
                }
                DialogUtils.getInstance().dismissCDialog();
                break;
            case R.id.tv_refuse:
                DialogUtils.getInstance().dismissCDialog();
                break;
            case R.id.tv_cancel:
                DialogUtils.getInstance().dismissCDialog();
                break;
        }
    }
}
